package com.ponxu.mb.web.action.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;
import com.ponxu.mb.model.Category;
import com.ponxu.mb.model.Post;
import com.ponxu.mb.model.User;
import com.ponxu.mb.service.CategoryService;
import com.ponxu.mb.service.PostService;
import com.ponxu.mb.web.action.MiniBlogAction;
import com.ponxu.utils.Lang;
import com.ponxu.utils.TimeUtils;
import com.ponxu.web.core.WebContext;

/**
 * 文章管理
 * 
 * @author xwz
 */
public class PostAction extends MiniBlogAction {
	private static final Log LOG = LogFactory.getLog();
	private static final String FTL_EDIT = "/admin/publish.ftl";

	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("post", new Post());
		return FTL_EDIT;
	}

	@SuppressWarnings("unchecked")
	public String save(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WebContext context = new WebContext(request, response);

		int id = context.getIntParameter("id");
		String saveStatus = context.getParameter("saveStatus");
		String title = context.getParameter("title");
		String type = context.getParameter("type");
		String seoTitle = context.getParameter("seoTitle");
		String content = context.getParameter("content");
		String abstracts = context.getParameter("abstracts");
		String[] categorys = request.getParameterValues("category");
		String[] tags = request.getParameterValues("tag");
		int top = context.getIntParameter("top");
		int pageOrder = context.getIntParameter("pageOrder");
		String status = context.getParameter("status");
		String password = context.getParameter("password");
		String commentStatus = context.getParameter("commentStatus");

		Post post = null;
		if (id == 0) {
			post = new Post();
		} else {
			post = PostService.getById(id);
		}

		User user = (User) context.sessionGet("admin");
		Date now = new Date();
		status = "publish".equals(saveStatus) ? status : saveStatus;

		// 填充内容
		post.setAbstracts(abstracts);
		post.setCommentStatus(commentStatus);
		post.setContent(content);
		post.setPageOrder(pageOrder);
		post.setPassword(password);
		post.setPostTime(now);
		post.setSeoTitle(seoTitle);
		post.setStatus(status);
		post.setTitle(title);
		post.setTop(top);
		post.setType(type);
		post.setUserId(user.getId());

		// 分类
		List<Category> list = new ArrayList<Category>();
		for (String cat : categorys) {
			Category t = new Category();
			t.setId(Integer.parseInt(cat));
			list.add(t);
		}
		post.setCats(list);

		// 标签
		if (Lang.isNotEmpty(tags)) {
			list = new ArrayList<Category>();
			for (String tag : tags) {
				Category t = new Category();
				t.setName(tag);
				t.setType("tag");
				list.add(t);
			}
			post.setTags(list);
		}

		if (id == 0) {
			id = PostService.add(post);
		} else {
			PostService.update(post);
		}

		int code = 1;
		String msg = "保存成功!";
		if (id == 0) {
			code = 0;
			msg = "保存失败!";
		} else if ("auto".equals(status)) {
			msg = "自动保存于 " + TimeUtils.format("yyyy-MM-dd HH:mm:ss", now);
		}

		JSONObject json = new JSONObject();
		json.put("code", code);
		json.put("msg", msg);
		json.put("id", id);
		context.writeJSON(json);

		return null;
	}

	/**
	 * 修改
	 */
	public String edit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WebContext context = new WebContext(request, response);
		int id = context.getIntParameter("id");
		LOG.debug("id=%d", id);

		Post post = PostService.getById(id);
		CategoryService.populateForPost(post);
		context.put("post", post);

		return FTL_EDIT;
	}

	private int[] getIds(HttpServletRequest request) {
		String[] idstr = request.getParameterValues("id");
		int size = idstr.length;
		int[] ids = new int[size];
		for (int i = 0; i < size; i++) {
			ids[i] = Integer.parseInt(idstr[i]);
		}
		return ids;
	}

	/**
	 * 批量删除
	 */
	public String delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int[] ids = getIds(request);
		PostService.deleteById(ids);

		new WebContext(request, response).redirect("/admin/index");
		return null;
	}

	/**
	 * 置顶
	 */
	public String top(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int[] ids = getIds(request);
		PostService.setTop(ids, PostService.TOP_YES);

		new WebContext(request, response).redirect("/admin/index");
		return null;
	}

	/**
	 * 取消置顶
	 */
	public String notop(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int[] ids = getIds(request);
		PostService.setTop(ids, PostService.TOP_NO);

		new WebContext(request, response).redirect("/admin/index");
		return null;
	}
}